<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>WebSocket Video Stream</title>
    <style>
      #videoCanvas {
        border: 1px solid black;
      }
    </style>
  </head>
  <body>
    <h1>WebSocket Video Stream</h1>
    <canvas id="videoCanvas" width="640" height="480"></canvas>
    <button id="startButton">Start Stream</button>
    <button id="stopButton">Stop Stream</button>

    <script>
      const canvas = document.getElementById("videoCanvas");
      const ctx = canvas.getContext("2d");
      var websocket;

      document.getElementById("startButton").addEventListener("click", () => {
        if (!websocket || websocket.readyState === WebSocket.CLOSED) {
          websocket = new WebSocket("ws://192.168.1.168:9393");
          websocket.binaryType = "arraybuffer";

          websocket.onmessage = (event) => {
            const arrayBuffer = event.data;
            const blob = new Blob([arrayBuffer], { type: "image/jpeg" });
            const url = URL.createObjectURL(blob);

            const img = new Image();
            img.onload = () => {
              ctx.clearRect(0, 0, canvas.width, canvas.height);
              ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
              URL.revokeObjectURL(url);
            };
            img.src = url;
          };

          websocket.onopen = () => {
            console.log("WebSocket connection opened");
          };

          websocket.onclose = () => {
            console.log("WebSocket connection closed");
          };
        }
      });

      document.getElementById("stopButton").addEventListener("click", () => {
        if (websocket) {
          websocket.send("stop");
          websocket.close();
        }
      });
    </script>
  </body>
</html>
